package com.steven.design.Builder_Pattern.singletons;

import java.util.concurrent.TimeUnit;

/**
 * 单例模式
 */
public class DoubleCheck {

    //加上volatile是为了防止指令重排序
    private static volatile DoubleCheck instance;

     public static DoubleCheck getInstance(){
         if (instance ==null){
             synchronized (DoubleCheck.class){
                 if (instance ==null){
                     try {
                         TimeUnit.SECONDS.sleep(2);
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                     }
                     instance = new DoubleCheck();
                 }
             }
         }
         return instance;
     }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                System.out.println(DoubleCheck.getInstance().hashCode());
            }).start();
        }

    }


}
